<!-- eslint-disable no-undef -->
<script setup>
import { ref } from 'vue'
import ArticleCateName from '@/views/article/components/ArticleCateName.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { artDetailService, artPublishService, artUpdateService } from '@/api/article'
import { baseURL } from '@/utils/request'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const visibleDrawer = ref(false)
// 定义默认数据
const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
}
const formModel = ref({ ...defaultForm })
const imageUrl = ref('')
const quillEditRef = ref()

async function imageUrloFileObject(imageUrl, filename) {
  try {
    // 使用axios下载图片数据
    const response = await axios.get(imageUrl,{ responseType: 'arraybuffer'})
    // 将下载的数据转换成Blob对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type']
    })
    // 创建file对象
    const file = new File([blob], filename, {
      type: response.headers['content-type']
    })
    return file
  } catch (error) {
    console.error('Error converting image URL File object:', error)
    return null
  }
}

const getArtDetail = async (id) => {
  const res = await artDetailService(id)
  console.log(res.data)
  formModel.value = res.data.data
  // 图片需要单独处理
  imageUrl.value = baseURL + formModel.value.cover_img
  // 将网络图片地址转换成file对象
  const file = await imageUrloFileObject(imageUrl.value, formModel.value.cover_img)
  formModel.value.cover_img = file
}

const open = (row) => {
    visibleDrawer.value = true
    // console.log(row)
    if (row.id) {
      // console.log('编辑回显')
      getArtDetail(row.id)
    } else {
      // 重置表单数据
      formModel.value = { ...defaultForm }
      // 重置图片和富文本数据
      imageUrl.value = ''
      quillEditRef.value.setHTML('')
      console.log('添加')
    }
}

const onSelectFile = (uploadFile) => {
  console.log(uploadFile)
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}

const emit = defineEmits(['success'])
const onPublish = async (state) => {
  formModel.value.state = state
  const fd = new FormData()
  // 将普通对象转换成formData对象
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  // 发送请求
  if (formModel.value.id) {
    // console.log('编辑操作')
    await artUpdateService(fd)
    ElMessage.success('修改成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    await artPublishService(fd)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    // 通知父组件，添加成功了
    emit('success', 'add')
  }
}

defineExpose({
  open
})

</script>
<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.cate_id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form label-width="100px">
      <el-form-item label="文章标题">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <article-cate-name width="100%" v-model="formModel.cate_id"></article-cate-name>
      <el-form-item label="文章封面">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="onSelectFile"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
      </el-form-item>
      <el-form-item label="文章内容">
        <div class="editor">
          <quill-editor ref="quillEditRef" theme="snow" v-model:content="formModel.content" content-type="html"></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
